'use strict'

const {http2cli} = require('gohttp')

class apilimit {

  constructor () {
    
    this.host = 'http://localhost:10101'

    this.max = 10

    this.hs = null

  }

  init () {
    this.hs = http2cli.connectPool(this.host, {
      keepalive: true,
      max : this.max,
      timeout: 0,
    })
  }

  async check (id, loop = 0) {

    let r = await this.hs.get({
      path : `/${id}`,
      timeout: 1280,
    })
    
    if ((r.timeout || r.status === 0) && loop < 1) {
      return await this.check(id, loop+1)
    }

    if (r.ok) {
      return true
    }

    return false

  }

  async getConfig () {
    let r = await this.hs.get({
      path : '/config',
      timeout: 1500,
    })

    if (r.ok) {
      return r.json()
    }

    return false
  }

  async setConfig (data) {

    let r = await this.hs.post({
      path : '/config',
      body : data,
      headers : {
        'content-type' : 'text/plain'
      }
    })

    if (r.ok) {
      return true
    }

    return false
  }

  async getAllow () {

  }

  async setAllow (data) {
    let r = await this.hs.post({
      path : '/allow',
      body : data,
      headers : {
        'content-type' : 'text/plain'
      }
    })
    
    if (r.ok) {
      return true
    }

    return false

  }

  async deleteAllow () {

  }

}

module.exports = apilimit
